<template>
  <div class="home_container">
    <header>
      <van-field
        class="home_search"
        v-model="searchText"
        clearable
        placeholder="搜索"
        :border="false"
        input-align="center"
        @click="searchClick"
      />
      <van-icon name="search" class="icon" />
    </header>
    <nav style="width: 100%;">
      <van-tabs
        v-model="active"
        :swipeable="true"
        :border="true"
        @click="tabsClick"
      >
        <van-tab :title="item.name" v-for="item in navLists" :key="item.id">
        </van-tab>
        <van-tab class="box"></van-tab>
      </van-tabs>
      <div class="humbuger" @click="btnChannelsClick">
        <van-icon name="wap-nav" size="20" />
      </div>
    </nav>
    <main>
      <!-- <pre>{{ RecommendChannelsLists }}</pre> -->
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" offset="400">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多数据了"
          @load="onload"
        >
          <van-cell
            v-for="(item, index) in RecommendChannelsLists"
            :key="index"
            :title="item.title"
            @click="ListClick(item.art_id)"
          >
            <template #label>
              <div v-if="item.cover.images.length === 3" class="image">
                <img
                  :src="img"
                  alt=""
                  v-for="(img, index) in item.cover.images"
                  :key="index"
                  style="width: 30%;"
                />
              </div>
              <span class="custom-title">
                &nbsp; &nbsp;&nbsp;{{ item.aut_name }}&nbsp;&nbsp;&nbsp;
              </span>
              <span class="custom-title">
                &nbsp;&nbsp;&nbsp;评论{{ item.like_count }}&nbsp;&nbsp;&nbsp;
              </span>
              <span class="custom-title">
                &nbsp;&nbsp;&nbsp;{{ item.pubdate | format }}&nbsp;&nbsp;&nbsp;
              </span>
            </template>
            <template #default v-if="item.cover.images.length === 1">
              <div>
                <img
                  :src="img"
                  alt=""
                  v-for="(img, index) in item.cover.images"
                  :key="index"
                  style="width: 100%;"
                />
              </div>
            </template>
          </van-cell>
        </van-list>
      </van-pull-refresh>
    </main>
    <!-- 弹出层 -->
    <van-popup
      :show="show"
      :popupStyle="popupStyle"
      :navLists="navLists"
      :allChannels="recommendChannels"
      @vanPopupclose="vanPopupclose"
      :active="active"
      @edmitNavLists="edmitNavLists"
      @edmitNavlistsClass="edmitNavlistsClass"
      @recommendChannelClick="recommendChannelClick"
    >
    </van-popup>
  </div>
</template>

<script>
import format from '@/untils/timeFormat.js'
import { apiHomeGetChannels, apiRecommendChannels, apiGetAllChannels } from '@/network'
// import mapState from 'vuex'
// 导入弹出层popup组件
import vanPopup from './components/homePopup'
// 导入存储token的函数
import setToken from '../../untils/setToken.js'
import getToken from '../../untils/getToken.js'
export default {
  name: 'Home',
  data () {
    return {
      searchText: '',
      navLists: [],
      active: 0,
      currentId: 0,
      RecommendChannelsLists: [],
      finished: false,
      refreshing: false,
      loading: false,
      timestamp: '',
      isPull: false,
      // 弹出层
      show: false,
      popupStyle: { height: '100%' },
      // 全部频道列表
      allChannels: [],
      // 是否登录
      isLogin: false
    }
  },
  created () {
    this.getChannels()
    if (this.$store.state.loginToken) {
      this.isLogin = true
    } else {
      this.isLogin = false
    }
  },
  methods: {
    // 如果没有登录但是能获取到本地缓存的值的话就用本地缓存的值，
    // 没有登录或者没有缓存的话，直接发送请求，获取默认的数组值
    async getChannels () {
      try {
        if (!this.isLogin) {
          if (getToken('myNavLists')) {
            this.navLists = JSON.parse(getToken('myNavLists'))
          }
        } else {
          const res = await apiHomeGetChannels()
          const { data: { data: { channels: lists } } } = res
          this.navLists = lists
          this.currentId = lists[0].id
        }
      } catch (err) {
        console.log(err)
      }
    },
    async RecommendChannels (id, widthTop) {
      const params = {
        channel_id: id,
        timestamp: this.timestamp || +new Date(),
        with_top: widthTop
      }
      try {
        const res = await apiRecommendChannels(params)
        const { data: { data: { results: lists } }, data: { data: { pre_timestamp: preTimestamp } } } = res
        if (this.isPull) {
          this.RecommendChannelsLists = lists
        } else {
          this.RecommendChannelsLists = this.RecommendChannelsLists.concat(lists)
        }
        this.isPull = false
        this.timestamp = preTimestamp
        this.loading = false
        this.refreshing = false
        // 如果数组的长度不为空则说明还有数据，this.finished为false
        if (lists.length === 0) {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取所有频道
    async  getAllChannels () {
      try {
        const res = await apiGetAllChannels()
        const { data: { data: { channels: lists } } } = res
        this.allChannels = lists
        // for (let i = 0; i < this.allChannels.length; i++) {
        //   for (let j = 0; j < this.navLists.length; j++) {
        //     if (this.allChannels[i].id === this.navLists[j].id) {
        //       this.allChannels.splice(i, 1)
        //       i--
        //       break
        //     }
        //   }
        // }
        console.log(this.allChannels)
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    tabsClick () {
      console.log(this.active)
      const id = this.navLists[this.active].id
      const widthTop = 1
      this.RecommendChannels(id, widthTop)
    },
    onRefresh () {
      this.loading = false
      this.isPull = true
      this.onload && this.onload()
    },
    onload () {
      this.refreshing = true
      let id = null
      if (this.navLists.length === 0) {
        id = 0
        return this.RecommendChannels(0, 1)
      } else {
        id = this.navLists[this.active].id
      }
      const widthTop = 1
      this.RecommendChannels(id, widthTop)
    },
    // 弹出层按钮
    btnChannelsClick () {
      this.show = true
      this.getAllChannels()
    },
    vanPopupclose () {
      this.show = false
    },
    // 修改我的频道数组
    edmitNavLists (index) {
      this.allChannels.push(this.navLists.splice(index, 1)[0])
      if (!this.isLogin) {
        setToken('myNavLists', this.navLists)
      }
    },
    // 频道子组件中点击修改父组件中的active值
    edmitNavlistsClass (index) {
      this.active = index
      this.show = false
    },
    // 删除推荐频道中选中的标签
    recommendChannelClick (index) {
      // this.navLists.push(this.allChannels.splice(index, 1))
      this.navLists.push(this.allChannels.splice(index, 1)[0])
      if (!this.isLogin) {
        setToken('myNavLists', this.navLists)
      }
      // console.log(this.allChannels.splice(index, 1))
      console.log(this.navLists)
    },
    // 点击跳转
    searchClick () {
      this.$router.push('/search')
    },
    // 点击列表内容区跳转到 Article页面
    ListClick (id) {
      this.$router.push(`/article/${id}`)
      // console.log(id)
    }
  },
  filters: {
    format
  },
  components: {
    vanPopup
  },
  computed: {
    recommendChannels () {
      const newChannels = this.allChannels.filter(item1 => {
        const res = this.navLists.some(item2 => item1.id === item2.id)
        if (!res) {
          return true
        }
      })
      //    recommendChannels () {
      //   return this.allChannels.filter(item1 => !this.navLists.some(item2 => item1.id === item2.id))
      // }
      // console.log(this.allChannels)
      // console.log(newChannels)
      return newChannels
    }
    // ...mapState(['loginToken'])

  }

}
</script>

<style lang="less" scoped>
.home_container {
  padding-top: 210px;
  overflow: hidden;
  header {
    display: flex;
    // display: none;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 120px;
    background-color: #3296fa;
    /deep/.home_search {
      width: 70%;
      height: 60px;
      padding: 0;
      line-height: 60px;
      text-align: center;
      background-color: rgba(255, 255, 255, 0.3);
      border-radius: 30px;
      .van-field__control {
        &::placeholder {
          color: #fff;
        }
      }
    }
    .van-icon-search {
      position: absolute;
      left: 50%;
      top: 50%;
      font-size: 30px;
      color: #fff;
      // margin-left: 20px;
      transform: translate(-70px, -50%);
    }
  }
  nav {
    display: flex;
    // display: none;
    position: fixed;
    top: 120px;
    left: 0;
    z-index: 2;
    /deep/.van-tabs {
      width: 100%;
      .van-tabs__wrap {
        border-bottom: 1px solid #eee;
        .van-tabs__nav {
          padding-bottom: 20px;
        }
      }
    }
    /deep/.van-tabs__nav {
      display: flex;
      .van-tab {
        width: 30%;
        border-right: 1px solid #ccc;
        &:nth-last-of-type(2) {
          width: 60px;
        }
        .van-tab__text {
          font-size: 25px;
        }
      }
    }
    .humbuger {
      display: flex;
      justify-content: center;
      align-items: center;
      position: absolute;
      top: 0;
      right: 0;
      width: 60px;
      height: 100%;
      background-color: rgba(255, 255, 255, 0.8);
      box-sizing: border-box;
      border-bottom: 1px solid #eee;
    }
    // 导航下的线
    /deep/.van-tabs__line {
      width: 40px;
      background-color: #3296fa;
      transform: translateY(-200px);
    }
  }
  main {
    overflow: hidden;
    /deep/.van-cell {
      padding-bottom: 0;
      padding-top: 5px;
      .van-cell__title {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .van-cell__label {
          margin: 10px 0 0;
        }
      }
    }

    .image {
      display: flex;
      width: 100%;
      img {
        width: 100%;
        max-height: 150px;
        margin: 0 15px 10px;
      }
    }
  }
}
</style>
